<template>
  <div id="app">
    <el-container class="app-container">
      <el-aside class="app-sidebar" :width="sidebarWidth">
        <div class="sidebar-header">
          <div v-if="!isCollapsed" class="sidebar-title">
            <h2 class="app-title">{{ $t('app.title') }}</h2>
            <span class="app-version">v{{ version }}</span>
          </div>
          <div v-else class="sidebar-icon">
            <i class="el-icon-link"></i>
          </div>
        </div>
        <el-menu
          :default-active="activeModule"
          class="sidebar-menu"
          @select="handleMenuSelect"
          :collapse="isCollapsed"
        >
          <el-menu-item index="dashboard">
            <i class="el-icon-s-home"></i>
            <span slot="title">{{ $t('menu.dashboard') }}</span>
          </el-menu-item>
          
          <el-submenu index="http">
            <template slot="title">
              <i class="el-icon-connection"></i>
              <span>{{ $t('menu.http') }}</span>
            </template>
            <el-menu-item index="http-client">
              <i class="el-icon-upload2"></i>
              <span slot="title">{{ $t('menu.httpClient') }}</span>
            </el-menu-item>
            <el-menu-item index="http-server">
              <i class="el-icon-download"></i>
              <span slot="title">{{ $t('menu.httpServer') }}</span>
            </el-menu-item>
          </el-submenu>

          <el-menu-item index="mqtt-client">
            <i class="el-icon-message"></i>
            <span slot="title">{{ $t('menu.mqttClient') }}</span>
          </el-menu-item>

          <el-menu-item index="websocket">
            <i class="el-icon-refresh"></i>
            <span slot="title">{{ $t('menu.websocket') }}</span>
          </el-menu-item>

          <el-submenu index="tcp-udp">
            <template slot="title">
              <i class="el-icon-share"></i>
              <span>TCP/UDP</span>
            </template>
            <el-menu-item index="tcp-client">
              <span slot="title">{{ $t('menu.tcpClient') }}</span>
            </el-menu-item>
            <el-menu-item index="tcp-server">
              <span slot="title">{{ $t('menu.tcpServer') }}</span>
            </el-menu-item>
            <el-menu-item index="udp-client">
              <span slot="title">{{ $t('menu.udpClient') }}</span>
            </el-menu-item>
            <el-menu-item index="udp-server">
              <span slot="title">{{ $t('menu.udpServer') }}</span>
            </el-menu-item>
          </el-submenu>

          <el-submenu index="tools">
            <template slot="title">
              <i class="el-icon-s-tools"></i>
              <span>{{ $t('menu.tools') }}</span>
            </template>
            <el-menu-item index="json-formatter">
              <i class="el-icon-document"></i>
              <span slot="title">{{ $t('menu.jsonFormatter') }}</span>
            </el-menu-item>
            <el-menu-item index="base64">
              <i class="el-icon-key"></i>
              <span slot="title">{{ $t('menu.base64') }}</span>
            </el-menu-item>
            <el-menu-item index="timestamp">
              <i class="el-icon-time"></i>
              <span slot="title">{{ $t('menu.timestamp') }}</span>
            </el-menu-item>
          </el-submenu>

          <el-menu-item index="history">
            <i class="el-icon-document-copy"></i>
            <span slot="title">{{ $t('menu.history') }}</span>
          </el-menu-item>

          <el-menu-item index="settings">
            <i class="el-icon-setting"></i>
            <span slot="title">{{ $t('menu.settings') }}</span>
          </el-menu-item>
        </el-menu>

        <div class="sidebar-footer">
          <el-button
            circle
            size="mini"
            @click="toggleSidebar"
            :icon="isCollapsed ? 'el-icon-s-unfold' : 'el-icon-s-fold'"
          ></el-button>
        </div>
      </el-aside>

      <el-container class="main-container">
        <el-header class="app-header">
          <div class="header-tabs" ref="tabsContainer">
            <el-tabs
              v-model="activeTab"
              type="card"
              @tab-remove="removeTab"
              @tab-click="handleTabClick"
            >
              <el-tab-pane
                v-for="tab in openTabs"
                :key="tab.id"
                :label="tab.title"
                :name="tab.id"
                :closable="tab.closable"
              >
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-header>

        <el-main class="app-main">
          <transition name="fade" mode="out-in">
            <keep-alive :include="cachedViews">
              <router-view :key="activeTab" />
            </keep-alive>
          </transition>
        </el-main>

        <el-footer class="app-footer" height="30px">
          <div class="footer-info">
            <span>{{ currentTime }}</span>
            <span class="separator">|</span>
            <span>{{ connectionStatus }}</span>
            <span class="separator">|</span>
            <span>{{ memoryUsage }}</span>
          </div>
        </el-footer>
      </el-container>
    </el-container>

    <EnvironmentDialog
      v-if="showEnvironmentDialog"
      @close="showEnvironmentDialog = false"
    />
    
    <SettingsDialog
      v-if="showSettingsDialog"
      @close="showSettingsDialog = false"
    />
    
    <!-- 右键菜单 - 移到根层级 -->
    <div
      v-show="contextMenuVisible"
      class="tab-context-menu"
      :style="contextMenuStyle"
      ref="contextMenu"
    >
      <div class="context-menu-item" @click="closeOtherTabs">
        <i class="el-icon-close"></i>
        关闭其他标签
      </div>
      <div class="context-menu-item" @click="closeAllTabs">
        <i class="el-icon-document-delete"></i>
        关闭所有标签
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import EnvironmentDialog from './components/dialogs/EnvironmentDialog.vue'
import SettingsDialog from './components/dialogs/SettingsDialog.vue'

export default {
  name: 'App',
  components: {
    EnvironmentDialog,
    SettingsDialog
  },
  data() {
    return {
      version: '1.0.0',
      isCollapsed: false,
      activeModule: 'dashboard',
      currentTime: '',
      memoryUsage: '',
      showEnvironmentDialog: false,
      showSettingsDialog: false,
      timer: null,
      contextMenuVisible: false,
      contextMenuStyle: {
        left: '0px',
        top: '0px'
      },
      rightClickedTab: null
    }
  },
  computed: {
    ...mapState('ui', ['openTabs', 'cachedViews']),
    ...mapState('connection', ['connectionStatus']),
    activeTab: {
      get() {
        return this.$store.state.ui.activeTab
      },
      set(value) {
        this.$store.commit('ui/SET_ACTIVE_TAB', value)
      }
    },
    sidebarWidth() {
      return this.isCollapsed ? '64px' : '240px'
    }
  },
  mounted() {
    this.initApp()
    this.startTimer()
    this.$nextTick(() => {
      this.bindTabRightClick()
    })
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.unbindTabRightClick()
  },
  methods: {
    ...mapActions('ui', ['addTab', 'removeTabAction', 'setActiveTab']),
    ...mapActions('modules', ['loadModule']),
    
    initApp() {
      if (window.require) {
        const { ipcRenderer } = window.require('electron')
        ipcRenderer.invoke('app:get-version').then(version => {
          this.version = version
        }).catch(() => {
          // Fallback version if IPC fails
          this.version = '1.0.0'
        })
      }
      
      this.loadSavedState()
    },

    startTimer() {
      this.updateTime()
      this.updateMemoryUsage()
      
      this.timer = setInterval(() => {
        this.updateTime()
        this.updateMemoryUsage()
      }, 1000)
    },

    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleTimeString('zh-CN')
    },

    updateMemoryUsage() {
      if (performance.memory) {
        const used = performance.memory.usedJSHeapSize
        const total = performance.memory.totalJSHeapSize
        const usedMB = (used / 1048576).toFixed(1)
        const totalMB = (total / 1048576).toFixed(1)
        this.memoryUsage = `${this.$t('app.memory')}: ${usedMB}/${totalMB} MB`
      } else {
        this.memoryUsage = `${this.$t('app.memory')}: N/A`
      }
    },

    handleMenuSelect(index) {
      this.activeModule = index
      // 添加标签页
      const moduleMap = {
        'dashboard': { titleKey: 'menu.dashboard', route: '/dashboard' },
        'http-client': { titleKey: 'menu.httpClient', route: '/http-client' },
        'http-server': { titleKey: 'menu.httpServer', route: '/http-server' },
        'mqtt-client': { titleKey: 'menu.mqttClient', route: '/mqtt-client' },
        'websocket': { titleKey: 'menu.websocket', route: '/websocket' },
        'tcp-client': { titleKey: 'menu.tcpClient', route: '/tcp-client' },
        'tcp-server': { titleKey: 'menu.tcpServer', route: '/tcp-server' },
        'udp-client': { titleKey: 'menu.udpClient', route: '/udp-client' },
        'udp-server': { titleKey: 'menu.udpServer', route: '/udp-server' },
        'json-formatter': { titleKey: 'menu.jsonFormatter', route: '/json-formatter' },
        'base64': { titleKey: 'menu.base64', route: '/base64' },
        'timestamp': { titleKey: 'menu.timestamp', route: '/timestamp' },
        'history': { titleKey: 'menu.history', route: '/history' },
        'settings': { titleKey: 'menu.settings', route: '/settings' }
      }
      const module = moduleMap[index]
      
      if (module) {
        // 只调用addTab一次，不调用loadModule避免重复
        this.addTab({
          id: index,
          title: this.$t(module.titleKey),
          route: module.route
        })
        
        // 避免重复导航到相同路由
        if (this.$route.path !== module.route) {
          this.$router.push(module.route).catch(err => {
            // 忽略重复导航错误
            if (err.name !== 'NavigationDuplicated') {
              console.error(err)
            }
          })
        }
      }
    },

    handleTabClick(tab) {
      this.setActiveTab(tab.name)
      const tabData = this.openTabs.find(t => t.id === tab.name)
      if (tabData && tabData.route) {
        // 避免重复导航到相同路由
        if (this.$route.path !== tabData.route) {
          this.$router.push(tabData.route).catch(err => {
            // 忽略重复导航错误
            if (err.name !== 'NavigationDuplicated') {
              console.error(err)
            }
          })
        }
      }
    },

    addNewTab() {
      const id = `tab_${Date.now()}`
      this.addTab({
        id,
        title: this.$t('app.newTab'),
        route: '/dashboard'
      })
    },

    removeTab(targetName) {
      // 找到要删除的标签
      const tabIndex = this.openTabs.findIndex(t => t.id === targetName)
      if (tabIndex === -1) return
      
      const isActiveTab = this.activeTab === targetName
      const tabCount = this.openTabs.length
      
      // 执行删除
      this.removeTabAction(targetName)
      
      // 如果删除的是当前激活的标签，需要导航到新的标签
      this.$nextTick(() => {
        if (isActiveTab) {
          // 获取删除后的新激活标签
          const newActiveTab = this.$store.state.ui.activeTab
          const newTab = this.openTabs.find(t => t.id === newActiveTab)
          
          if (newTab && newTab.route) {
            if (this.$route.path !== newTab.route) {
              this.$router.push(newTab.route).catch(err => {
                if (err.name !== 'NavigationDuplicated') {
                  console.error(err)
                }
              })
            }
          } else if (tabCount === 1) {
            // 如果是最后一个标签，导航到仪表盘
            if (this.$route.path !== '/dashboard') {
              this.$router.push('/dashboard').catch(err => {
                if (err.name !== 'NavigationDuplicated') {
                  console.error(err)
                }
              })
            }
          }
        }
      })
    },

    toggleSidebar() {
      this.isCollapsed = !this.isCollapsed
    },

    openEnvironmentManager() {
      this.showEnvironmentDialog = true
    },

    openGlobalSettings() {
      this.showSettingsDialog = true
    },

    openAbout() {
      this.$message({
        message: 'LinkVerify v1.0.0 - Multi-Service Communication Debug Tool',
        type: 'info',
        duration: 3000
      })
    },

    loadSavedState() {
      const savedState = localStorage.getItem('appState')
      if (savedState) {
        try {
          const state = JSON.parse(savedState)
          this.activeModule = state.activeModule || 'dashboard'
          this.isCollapsed = state.isCollapsed || false
        } catch (e) {
          console.error('Failed to load saved state:', e)
        }
      }
    },

    saveState() {
      const state = {
        activeModule: this.activeModule,
        isCollapsed: this.isCollapsed
      }
      localStorage.setItem('appState', JSON.stringify(state))
    },

    bindTabRightClick() {
      // 绑定右键事件到实际的标签元素
      this.$nextTick(() => {
        const tabElements = this.$refs.tabsContainer?.querySelectorAll('.el-tabs__item')
        if (tabElements) {
          tabElements.forEach(tabElement => {
            tabElement.addEventListener('contextmenu', this.handleTabRightClick)
          })
        }
      })
    },

    unbindTabRightClick() {
      const tabElements = this.$refs.tabsContainer?.querySelectorAll('.el-tabs__item')
      if (tabElements) {
        tabElements.forEach(tabElement => {
          tabElement.removeEventListener('contextmenu', this.handleTabRightClick)
        })
      }
    },

    handleTabRightClick(event) {
      event.preventDefault()
      
      // 从 DOM 元素获取标签 ID，Element UI 使用 aria-controls 属性
      const tabElement = event.currentTarget
      const ariaControls = tabElement.getAttribute('aria-controls')
      const tabId = ariaControls?.replace('pane-', '') || 
                   tabElement.getAttribute('id')?.replace('tab-', '') ||
                   tabElement.textContent?.trim()
      
      let tab = null
      if (tabId) {
        tab = this.openTabs.find(t => t.id === tabId)
      }
      
      // 如果通过属性找不到，尝试通过元素位置找到对应的标签
      if (!tab) {
        const allTabs = Array.from(tabElement.parentElement.children)
        const tabIndex = allTabs.indexOf(tabElement)
        if (tabIndex >= 0 && tabIndex < this.openTabs.length) {
          tab = this.openTabs[tabIndex]
        }
      }
      
      if (tab) {
        this.rightClickedTab = tab
        
        // 先显示菜单（位置为0,0）
        this.contextMenuVisible = true
        
        // 在下一个tick中计算准确位置
        this.$nextTick(() => {
          const menu = this.$refs.contextMenu
          if (!menu) return
          
          // 获取菜单实际尺寸
          const menuRect = menu.getBoundingClientRect()
          const menuWidth = menuRect.width || 150
          const menuHeight = menuRect.height || 80
          
          // 使用 clientX/clientY (相对于视口的坐标)
          let x = event.clientX
          let y = event.clientY
          
          // 获取视口尺寸
          const viewportWidth = window.innerWidth
          const viewportHeight = window.innerHeight
          
          // 检查并调整位置，确保菜单完全在视口内
          if (x + menuWidth > viewportWidth) {
            x = x - menuWidth  // 显示在鼠标左侧
          }
          
          if (y + menuHeight > viewportHeight) {
            y = y - menuHeight  // 显示在鼠标上方
          }
          
          // 确保不超出左边和上边
          if (x < 0) x = 0
          if (y < 0) y = 0
          
          // 设置最终位置
          this.contextMenuStyle.left = x + 'px'
          this.contextMenuStyle.top = y + 'px'
        })
        
        // 点击其他地方隐藏菜单
        document.addEventListener('click', this.hideContextMenu)
      }
    },

    hideContextMenu() {
      this.contextMenuVisible = false
      this.rightClickedTab = null
      document.removeEventListener('click', this.hideContextMenu)
    },

    closeOtherTabs() {
      const currentTabId = this.rightClickedTab?.id
      if (!currentTabId) return
      
      // 获取所有可关闭的标签（除了当前标签和仪表盘）
      const tabsToClose = this.openTabs.filter(tab => 
        tab.id !== currentTabId && 
        tab.id !== 'dashboard' && 
        tab.closable !== false
      )
      
      // 逐个关闭标签
      tabsToClose.forEach(tab => {
        this.removeTabAction(tab.id)
      })
      
      this.hideContextMenu()
    },

    closeAllTabs() {
      // 获取所有可关闭的标签（除了仪表盘）
      const tabsToClose = this.openTabs.filter(tab => 
        tab.id !== 'dashboard' && 
        tab.closable !== false
      )
      
      // 逐个关闭标签
      tabsToClose.forEach(tab => {
        this.removeTabAction(tab.id)
      })
      
      // 如果当前不在仪表盘，切换到仪表盘
      if (this.activeTab !== 'dashboard') {
        this.setActiveTab('dashboard')
        if (this.$route.path !== '/dashboard') {
          this.$router.push('/dashboard').catch(err => {
            if (err.name !== 'NavigationDuplicated') {
              console.error(err)
            }
          })
        }
      }
      
      this.hideContextMenu()
    }
  },
  watch: {
    activeModule() {
      this.saveState()
    },
    isCollapsed() {
      this.saveState()
    },
    openTabs: {
      handler() {
        // 当标签变化时，重新绑定右键事件
        this.$nextTick(() => {
          this.unbindTabRightClick()
          this.bindTabRightClick()
        })
      },
      deep: true
    },
    '$route'(to) {
      // 根据路由更新激活的标签和菜单
      const path = to.path.substring(1) // 移除开头的/
      if (path) {
        this.activeModule = path
        // 检查是否有对应的标签，如果有则激活它
        const tab = this.openTabs.find(t => t.route === to.path)
        if (tab) {
          this.setActiveTab(tab.id)
        }
      }
    }
  }
}
</script>

<style lang="scss">
@import './styles/variables.scss';
@import './styles/micro-interactions.scss';

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

#app {
  height: 100vh;
  overflow: hidden;
  background: $main-bg;
}

.app-container {
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.app-sidebar {
  background: $sidebar-bg;
  backdrop-filter: blur(10px);
  border-right: none;
  display: flex;
  flex-direction: column;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow-x: hidden;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);

  .sidebar-header {
    padding: 24px;
    text-align: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    min-height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, $primary-lighter 0%, transparent 100%);

    .sidebar-title {
      animation: fadeIn 0.5s ease;
      
      .app-title {
        font-size: 22px;
        font-weight: 700;
        background: linear-gradient(135deg, $primary-color, $primary-dark);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin: 0;
        letter-spacing: -0.5px;
      }

      .app-version {
        font-size: 12px;
        color: $text-secondary;
        margin-top: 4px;
        opacity: 0.8;
      }
    }

    .sidebar-icon {
      i {
        font-size: 36px;
        background: linear-gradient(135deg, $primary-color, $primary-dark);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        animation: pulse 2s infinite;
      }
    }
  }

  .sidebar-menu {
    flex: 1;
    border: none;
    background: transparent;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 12px;
    width: 100%;

    .el-menu-item, .el-submenu__title {
      height: 50px;
      line-height: 50px;
      border-radius: 10px;
      margin-bottom: 4px;
      transition: all 0.3s ease;
      font-weight: 500;
      
      &:hover {
        background: $hover-bg !important;
        transform: translateX(4px);
      }
      
      i {
        font-size: 18px;
        margin-right: 12px;
      }
    }

    .el-menu-item.is-active {
      background: linear-gradient(135deg, $primary-light, $primary-lighter) !important;
      color: $primary-color !important;
      font-weight: 600;
      box-shadow: 0 2px 8px rgba(74, 144, 226, 0.2);
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 60%;
        background: $primary-color;
        border-radius: 0 4px 4px 0;
      }
    }
  }

  .sidebar-footer {
    padding: 16px;
    text-align: center;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(255, 255, 255, 0.02);
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: rotate(180deg);
        background: $primary-light;
        border-color: $primary-color;
      }
    }
  }
}

.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.app-header {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid $border-lighter;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  z-index: 100;

  .header-tabs {
    flex: 1;
    display: flex;
    align-items: center;
    position: relative;
    overflow: hidden;
    overflow-x:auto ;
    .el-tabs {
      flex: 1;
      
      .el-tabs__header {
        margin: 0;
        border: none;
      }

      .el-tabs__nav {
        border: none !important;
      }

      ::v-deep .el-tabs__item {
        border: none !important;
        height: 42px !important;
        line-height: 42px !important;
        flex-shrink: 0 !important;
        min-width: max-content !important;
        font-weight: 500;
        margin: 0 4px;
        border-radius: 8px 8px 0 0;
        transition: all 0.3s ease;
        
        &.is-active {
          background: $primary-lighter;
          color: $primary-color;
          font-weight: 600;
        }
        
        &:hover:not(.is-active) {
          background: $hover-bg;
        }
      }
    }

    .add-tab-btn {
      margin: 0 10px;
    }
  }

  .header-actions {
    padding: 0 20px;

    .el-dropdown-link {
      cursor: pointer;
      font-size: 20px;
      color: $text-primary;

      &:hover {
        color: $primary-color;
      }
    }
  }
}

.app-main {
  flex: 1;
  padding: 0;
  overflow: auto;
  background: linear-gradient(180deg, $border-extra-light 0%, $main-bg 100%);
}

.app-footer {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid $border-lighter;
  display: flex;
  align-items: center;
  padding: 0 24px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);

  .footer-info {
    font-size: 12px;
    color: $text-secondary;

    .separator {
      margin: 0 10px;
      color: $border-color;
    }
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.tab-context-menu {
  position: fixed;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 4px 0;
  z-index: 2000;
  min-width: 140px;

  .context-menu-item {
    padding: 8px 16px;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;

    i {
      font-size: 14px;
      width: 16px;
      text-align: center;
    }

    &:hover {
      background-color: #f5f7fa;
      color: #409eff;
    }

    &:active {
      background-color: #ecf5ff;
    }
  }
}
</style>